<template>
  <div>
    <!-- 筛选组件 -->
    <product-filter :brands="brands" @onFilter="handleFilter" />

    <!-- 商品列表 -->
    <el-row :gutter="20">
      <el-col :span="8" v-for="product in filteredProducts" :key="product.productID">
        <el-card>
          <h3>{{ product.productName }}</h3>
          <p>描述：{{ product.description }}</p>
          <p>库存数量：{{ product.stockQuantity }}</p>
          <p>平均采购价格：{{ product.averagePurchasePrice }}</p>
          <p>平均销售价格：{{ product.averageSalePrice }}</p>
          <p>总出库数量：{{ product.totalStockOutQuantity }}</p>
          <p>一级品牌：{{ product.brandName }}</p>
          <p>二级品牌：{{ product.subBrandName }}</p>
          <el-button type="primary" @click="openEditDialog(product)">更改</el-button>
          <el-button type="danger" @click="deleteProduct(product.productID)">删除</el-button>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <el-pagination
      @current-change="fetchProducts"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totalProducts"
      layout="prev, pager, next"
    />

    <!-- 编辑商品弹窗 -->
    <el-dialog title="编辑商品" v-model="editDialogVisible" width="50%">
      <el-form :model="editFormData" label-width="120px">
        <el-form-item label="商品名称">
          <el-input v-model="editFormData.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="二级分类ID">
          <el-input v-model="editFormData.subCategoryID" placeholder="请输入二级分类ID" />
        </el-form-item>
        <el-form-item label="图片路径">
          <el-input v-model="editFormData.imagePath" placeholder="请输入图片路径" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editFormData.description" type="textarea" placeholder="请输入商品描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateProduct">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { useProductStore } from '../stores/productStore';
import ProductFilter from './ProductFilter.vue';

export default {
  components: {
    ProductFilter,
  },
  props: {
    initialPageSize: {
      type: Number,
      default: 10,
    },
  },
  setup(props) {
    const store = useProductStore();

    // 商品数据
    const products = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(props.initialPageSize);
    const totalProducts = ref(0);

    // 品牌数据
    const brands = computed(() => store.brands);

    // 筛选条件
    const filterData = ref({
      brandName: '',
      subBrandName: '',
      minPrice: null,
      maxPrice: null,
    });

    // 编辑弹窗
    const editDialogVisible = ref(false);
    const editFormData = reactive({
      productID: null,
      productName: '',
      subCategoryID: null,
      imagePath: '',
      description: '',
    });

    // 获取商品数据
    const fetchProducts = async (page = 1) => {
      try {
        await store.fetchProducts(page);
        products.value = store.products;
        totalProducts.value = store.totalProducts;
        currentPage.value = store.currentPage;
      } catch (error) {
        console.error('加载商品数据失败:', error);
      }
    };

    // 打开编辑弹窗
    const openEditDialog = (product) => {
      editFormData.productID = product.productID;
      editFormData.productName = product.productName;
      editFormData.subCategoryID = product.subCategoryID;
      editFormData.imagePath = product.imagePath;
      editFormData.description = product.description;
      editDialogVisible.value = true;
    };

    // 更新商品
    const updateProduct = async () => {
      try {
        await store.updateProduct(editFormData.productID, {
          productID: editFormData.productID,
          productName: editFormData.productName,
          subCategoryID: editFormData.subCategoryID,
          imagePath: editFormData.imagePath,
          description: editFormData.description,
        });
        editDialogVisible.value = false;
        fetchProducts(currentPage.value); // 刷新商品列表
      } catch (error) {
        console.error('更新商品失败:', error);
      }
    };

    // 删除商品
    const deleteProduct = async (productId) => {
      try {
        await store.deleteProduct(productId);
        fetchProducts(currentPage.value); // 刷新商品列表
      } catch (error) {
        console.error('删除商品失败:', error);
      }
    };

    // 筛选商品
    const handleFilter = (filter) => {
      filterData.value = filter;
    };

    // 计算筛选后的商品列表
    const filteredProducts = computed(() => {
      return products.value.filter((product) => {
        const matchesBrandName =
          !filterData.value.brandName || product.brandName === filterData.value.brandName;
        const matchesSubBrandName =
          !filterData.value.subBrandName || product.subBrandName === filterData.value.subBrandName;
        const matchesMinPrice =
          filterData.value.minPrice === null || product.averageSalePrice >= filterData.value.minPrice;
        const matchesMaxPrice =
          filterData.value.maxPrice === null || product.averageSalePrice <= filterData.value.maxPrice;

        return matchesBrandName && matchesSubBrandName && matchesMinPrice && matchesMaxPrice;
      });
    });

    onMounted(() => {
      fetchProducts();
    });

    return {
      products,
      currentPage,
      pageSize,
      totalProducts,
      brands,
      editDialogVisible,
      editFormData,
      fetchProducts,
      openEditDialog,
      updateProduct,
      deleteProduct,
      handleFilter,
      filteredProducts,
    };
  },
};
</script>
